package com.jtjrenren.android.taxi.passenger.core.order.status;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.model.LatLng;
import com.jtjrenren.android.taxi.passenger.Constants;
import com.jtjrenren.android.taxi.passenger.R;
import com.jtjrenren.android.taxi.passenger.base.BaseApplication;
import com.jtjrenren.android.taxi.passenger.bean.api.ApiOrderDetails;
import com.jtjrenren.android.taxi.passenger.bean.api.CurrentOrderCost;
import com.jtjrenren.android.taxi.passenger.bean.api.DriverToCustomer;
import com.jtjrenren.android.taxi.passenger.bean.event.LocationEvent;
import com.jtjrenren.android.taxi.passenger.bean.protocl.CommonResponse;
import com.jtjrenren.android.taxi.passenger.bean.protocl.OrderAmountResponse;
import com.jtjrenren.android.taxi.passenger.bean.protocl.OrderDriverCancleResponse;
import com.jtjrenren.android.taxi.passenger.bean.protocl.OrderDriverIncomeResponse;
import com.jtjrenren.android.taxi.passenger.bean.protocl.OrderPassgerIncarResponse;
import com.jtjrenren.android.taxi.passenger.manger.AppManger;
import com.jtjrenren.android.taxi.passenger.manger.api.ApiWorks;
import com.jtjrenren.android.taxi.passenger.manger.push.cmd.ControlCmd;
import com.jtjrenren.android.taxi.passenger.manger.push.cmd.Protocl;
import com.jtjrenren.android.taxi.passenger.utils.AppConfig;
import com.jtjrenren.android.taxi.passenger.utils.ModuleAdapter;
import com.jtjrenren.android.taxi.passenger.utils.ModuleUtils;

import com.library.mvp.presenter.BasePresenter;
import com.library.utils.LogUtil;
import com.library.utils.StringUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Created by wdl on 2016/9/18.
 */

public class OrderStatusPresenterImpl extends BasePresenter<OrderStatusView, OrderStatusInteractor> implements OrderStatusPresenter {
    private ApiOrderDetails.MsgEntity orderDetails;
    private BDLocation currentLocation;
    private CurrentOrderCost.DataListEntity costRunning;

    public OrderStatusPresenterImpl(OrderStatusView view) {
        super(view);
    }


    @Override
    public OrderStatusInteractor createInteractor() {
        return new OrderStatusInteractorImpl();
    }

    @Override
    public void init() {
        EventBus.getDefault().register(this);
        currentLocation = AppManger.getInstance().currentLocation;
        view.refreshMapCenter(AppConfig.getLastRemLocation(BaseApplication.getInstance().getApplicationContext()));
    }

    @Override
    public void initOrder(String orderID) {
        if (StringUtils.isEmpty(orderID)) {
            view.showTip("数据异常，请稍后再试..");
            return;
        }
        view.showWaittingView("数据加载中....");
        interactor.getOrderDetails(orderID, new ApiWorks.ResponseListener<ApiOrderDetails>() {
            @Override
            public void onResponse(ApiOrderDetails apiOrderDetails) {
                view.dissWaittingView();
                if (apiOrderDetails != null && apiOrderDetails.getMsg() != null) {
                    LogUtil.log("order", apiOrderDetails.getMsg().toString());
                    orderDetails = apiOrderDetails.getMsg();
                    showCommon();
                    handReceiveOrderDetails(orderDetails);

                } else {
                    view.showTip("数据获取异常，请稍后再试...");
                }
            }
        });
    }

    @Override
    public void destory() {
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void handReceiveOrderDetails(ApiOrderDetails.MsgEntity receiveOrderDetails) {
        int status = Integer.parseInt(receiveOrderDetails.getStatus());
        switch (status) {
            case Constants.ORDER_STATUS_DISPATCH_WAITING://待调度
            case Constants.ORDER_STATUS_DISPATCH_ING://正在调度
            case Constants.ORDER_STATUS_DISPATCH_FINISH://调度完成
                orderNotStart();
                break;
            case Constants.ORDER_STATUS_PICKUP_PASSGER://去接乘客(终端:开始处理订单)
                driverComing();
                break;
            case Constants.ORDER_STATUS_INCAR://正在接送
                inCar();
                break;
            case Constants.ORDER_STATUS_FINISH://订单成功完成
            case Constants.ORDER_STATUS_ORDER_CRASHPAY://现金支付
            case Constants.ORDER_STATUS_PASSGER_INCARORPAY://司机已经提交乘客支付
                if (ModuleUtils.getPayStatus(orderDetails.getPayStatus()) == -1 && orderDetails.getOrderType().equals("2")) {
                    inCar();
                } else
                    orderFinish();
                break;
            case Constants.ORDER_STATUS_CANCLE_BEFOREDISPATCH://订单承接前乘客取消
            case Constants.ORDER_STATUS_CANCLE_AFTERDRIVER_ACCEPTE://订单承接后乘客取消
                view.showTsView(false);
                closeOrder(AppManger.getInstance().getString(R.string.dingdanquxiao));
                break;
            case Constants.ORDER_STATUS_CANCLE_BYDRIVER://订单承接后司机取消
                view.showTsView(true);
                closeOrder(AppManger.getInstance().getString(R.string.sijiquxiao));
                break;
            case Constants.ORDER_STATUS_FINISH_FORCE://强制完成 (订单失效)
            case Constants.ORDER_STATUS_CLOSE_BYPLATFORM://平台关闭（手动关闭）
                view.showTsView(false);
                closeOrder(AppManger.getInstance().getString(R.string.pingtaiguanbi));
                break;
        }
    }

    //订单还没有开始
    private void orderNotStart() {
        view.clearStatusView();
        view.showOrderNotStart();
    }

    @Override
    public void showCommon() {
        view.showCommon(orderDetails);
        if (Integer.parseInt(orderDetails.getOrderType()) == Constants.CARTYPE_SPECAR) {
            view.refreshSpecarView();
        } else {
            view.refreshTaxiView();
        }
    }

    @Override
    public void driverComing() {
        view.clearStatusView();
        view.showDriverComing();
        view.startGetDriverPostion();
    }

    private boolean inCar = false;

    @Override
    public void inCar() {
        view.clearStatusView();
        view.showInCar(orderDetails);

        inCar = true;

        //在这里跑路的状态专车和出租车不同，现在出租车不需要实时计费 专车需要
        if (Integer.parseInt(orderDetails.getOrderType()) == Constants.CARTYPE_SPECAR) {
            view.showInCarSpecar();
            view.startGetCost();
        } else {
            view.showInCarTaxi();
        }
    }

    @Override
    public void getCostSpecar() {
        interactor.getRuningCost(orderDetails.getOrderID(), new ApiWorks.ResponseListener<CurrentOrderCost>() {
            @Override
            public void onResponse(CurrentOrderCost currentOrderCost2) {

                if (currentOrderCost2 != null && currentOrderCost2.getDataList() != null && currentOrderCost2.getDataList().size() > 0) {
                    costRunning = currentOrderCost2.getDataList().get(0);
                    view.refreshRunDetails(costRunning);
                }
            }
        });
    }

    @Override
    public void closeOrder(String reason) {
        view.showCloseView(reason);
    }

    @Override
    public void orderFinish() {
        view.clearStatusView();
        view.showFinishView(orderDetails);


        int pjstatus = Integer.parseInt(StringUtils.isEmpty(orderDetails.getEvaluationstatus()) ? "0" : orderDetails.getEvaluationstatus());
        if (pjstatus == 0)
            view.refreshPjView(true);
        else {
            view.refreshPjView(false);
            int count = Integer.parseInt(StringUtils.isEmpty(orderDetails.getLevel()) ? "0" : orderDetails.getLevel());
            count = ModuleAdapter.changeevServiceLevelToLocL(count);
            view.showPjContent(count, StringUtils.isEmpty(orderDetails.getContents()) ? "" : orderDetails.getContents());
        }

        int paystatus = Integer.parseInt(StringUtils.isEmpty(orderDetails.getPayStatus()) ? "0" : orderDetails.getPayStatus());
        if (orderDetails.getStatus().equals("11"))
            paystatus = 1;


        if (paystatus == 0)
            view.refershPayView(false, "未支付");
        else view.refershPayView(true, "已支付");

        if (Integer.parseInt(orderDetails.getOrderType()) == Constants.CARTYPE_SPECAR) {
            view.refreshSpecarCostView(true);
            view.refreshOrderCost(true, orderDetails.getAmount());
        } else {
            view.refreshOrderCost(false, "");
        }

    }

    @Override
    public void getDriverPostion() {
        if (this.currentLocation != null) {
            LatLng target = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
            interactor.getDriverPos(orderDetails.getDriversID(), target, new ApiWorks.ResponseListener<DriverToCustomer>() {
                @Override
                public void onResponse(DriverToCustomer driverToCustomer) {
                    if (driverToCustomer != null && driverToCustomer.getResult() != null && driverToCustomer.getResult().size() > 0) {
                        DriverToCustomer.ResultEntity resultEntity = driverToCustomer.getResult().get(0);
                        view.refershDriverPostion(new LatLng(Double.parseDouble(resultEntity.getLat()), Double.parseDouble(resultEntity.getLog())), resultEntity.getTimelongs());
                    }
                }
            });
        }
    }

    @Override
    public String getXcgjUrl() {
        String urls = AppManger.getInstance().getString(R.string.url_xcgj) + "?Id=" + orderDetails.getOrderID() + "&year="
                + orderDetails.getCreateDate().substring(0, 4);
        LogUtil.log("order", "行车轨迹：" + urls);
        return urls;
    }

    @Override
    public String getSfbzUrl() {
        String url = ModuleUtils.getSfBzUrl(orderDetails.getStartLat(),
                orderDetails.getStartLng(), orderDetails.getCarType());
        return url;
    }

    @Override
    public String getDriverPhone() {
        return orderDetails.getContactMobile();
    }

    @Override
    public String getOrderID() {
        return orderDetails.getOrderID();
    }

    @Override
    public String getDriverID() {
        return orderDetails.getDriversID();
    }

    @Override
    public String getCostDesc() {
        String desc = orderDetails.getPayDetailInfos();
        if (costRunning != null)
            desc = costRunning.getFeeDesc();
        return desc;
    }

    @Override
    public void pay() {
        view.goPayPage(orderDetails.getOrderID());
    }

    @Override
    public void cancleOrder(int reason) {
        String cmd = ControlCmd.getCancleOrderCmd(orderDetails.getOrderID(), reason);
        AppManger.getInstance().sendMsgToControl(cmd);
    }

    @Override
    public void clearStatus() {
        inCar = false;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handLocEvent(LocationEvent event) {
        currentLocation = event.getLocation();
        if (inCar)
            view.refreshLocMark(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handDriverIncomeEvent(OrderDriverIncomeResponse orderDriverIncomeResponse) {
        if (orderDetails.getOrderID().equals(orderDriverIncomeResponse.getOrderSerialNo()))
            driverComing();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handDriverCancleEvent(OrderDriverCancleResponse orderDriverCancleResponse) {
        if (orderDetails.getOrderID().equals(orderDriverCancleResponse.getOrderSerialNo())) {
            view.showTsView(true);
            closeOrder(AppManger.getInstance().getString(R.string.sijiquxiao));
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handAomount(OrderAmountResponse amountResponse) {
        if (orderDetails.getOrderID().equals(amountResponse.getOrderSerialNo())) {
            String tipsTotal = amountResponse.getTipAmount();
            String total = amountResponse.getPayAmount();
            double price = 0;
            if (!StringUtils.isEmpty(tipsTotal))
                price += Double.parseDouble(tipsTotal);
            if (!StringUtils.isEmpty(total))
                price += Double.parseDouble(total);

            orderDetails.setTipsTotal(Double.parseDouble(amountResponse.getTipAmount()) + "");
            orderDetails.setAmount(price + "");
            orderDetails.setUsedTime(Double.parseDouble(amountResponse.getUseTime()) + "");
            orderDetails.setTaxiStandDistance(Double.parseDouble(amountResponse.getTotalDistance()) + "");
            orderDetails.setEvaluationstatus("0");
            orderDetails.setPayStatus(amountResponse.getPayStatus() == 2 ? "1" : "0");
            orderDetails.setCustomerPayId(amountResponse.getPrePayNo());

            orderFinish();
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handPassgerIncarEvent(OrderPassgerIncarResponse passgerIncarResponse) {
        if (orderDetails.getOrderID().equals(passgerIncarResponse.getOrderSerialNo()))
            inCar();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handPassgerCommon(CommonResponse commonResponse) {
        if (orderDetails.getOrderID().equals(commonResponse.getOrderSerialID()) &&
                Protocl.MSG_ID_ORDERCANCLE.equals(commonResponse.getCmdId())) {
            view.showTsView(false);
            closeOrder(AppManger.getInstance().getString(R.string.chengkequxiao));
        }
    }
}
